// Local Include File
#include <pcapgether.h>

// Standard C Include
#include <signal.h>
#include <stdlib.h>
#include <pcap.h>
#include <sys/time.h>
#include <pthread.h>
#include <net/ethernet.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>

// Stnand C++ Include
#include <iostream>


// STL Include
#include <vector>

using namespace std;

vector<InOutCount> PortCount;
InOutCount Count;

void *pcapgther(void *data)
{
	char errbuf[PCAP_ERRBUF_SIZE];
	int ret;
	char *dev;
	struct pcap_pkthdr hdr;
	struct ip *iph;
	struct tcphdr *tcph;
	struct bpf_program fp;

	const u_char *packet;
	struct ether_header *ep;

	char service[80] = {0x00,};
	int portnum = atoi((char *)data);

	bpf_u_int32 netp;
	bpf_u_int32 maskp;
	pcap_t *pcd;

	memset((void *)&Count, 0x00, sizeof(InOutCount));
	dev = pcap_lookupdev(errbuf);
	if (dev == NULL)
	{
		printf("%s\n", errbuf);
	}

	ret = pcap_lookupnet(dev, &netp, &maskp, errbuf);

	pcd = pcap_open_live(dev, BUFSIZ, NONPROMISCUOUS, -1, errbuf);
	if (pcd == NULL)
	{
		printf("%s\n", errbuf);
		exit(1);
	}

	sprintf(service, "port %s", data);
	if (pcap_compile(pcd, &fp, (char *)service, 0, netp) == -1)
	{
		printf("compile error\n");
		exit(1);
	}
	pcap_setfilter(pcd, &fp);

	for(;packet = (const unsigned char *)pcap_next(pcd, &hdr);)
	{
		ep = (struct ether_header *)packet;
		
		packet += sizeof(struct ether_header);
		iph = (struct ip *)packet;
		tcph = (struct tcphdr *)(packet + iph->ip_hl *4);
		if(ntohs(tcph->dest) == portnum)
		{
			Count.inbps += ntohs(iph->ip_len);
			Count.inpps ++;
		}
		else
		{
			Count.outbps += ntohs(iph->ip_len);
			Count.outpps ++;
		}
	}
}
